package com.rupertjones.globalcron.web;

import com.rupertjones.globalcron.domain.Setting;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.springframework.security.access.prepost.PreAuthorize;

/**
 * <p>&copy Rupert Jones 2011,2012</p>
 *
 * @author rup
 */
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class EditSettingAction extends AbstractFormAction {

    @ValidateNestedProperties({
        @Validate(field = "type", required = true, on = { "SaveOrUpdate" }),
        @Validate(field = "name", required = true, on = { "SaveOrUpdate" }),
        @Validate(field = "description", required = true, on = { "SaveOrUpdate" }),
        @Validate(field = "value", required = true, mask = "(true|false)", on = { "SaveOrUpdate" })
    })
    private Setting setting;

    @Before(stages = LifecycleStage.BindingAndValidation)
    public void loadAndBind() {
        String id = getContext().getRequest().getParameter("setting.id");
        int settingId = Integer.parseInt(id);
        setting = getSettingsService().find(settingId);
    }

    public Setting getSetting() {
        return setting;
    }

    @DefaultHandler
    public Resolution view() {
        return new ForwardResolution("/WEB-INF/jsp/edit_setting.jsp");
    }

    @HandlesEvent("SaveOrUpdate")
    public Resolution onSave() {
        getSettingsService().save(setting);
        return new ForwardResolution("InfoSettings.action");
    }
}
